package com.dge.app.providers;

import com.dge.app.ResourceTable;
import com.dge.app.common.URLConstants;
import com.dge.app.common.UserInfoMgr;
import com.dge.app.slice.WebViewAbilitySlice;
import com.dge.app.utils.SizeUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.webengine.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;

public class StatisticPanelProvider extends RecycleItemProvider {
    static final HiLogLabel label = new HiLogLabel(HiLog.DEBUG, 0x00201, "StatisticPanelProvider"); // MY_MODULE=0x00201
    private ArrayList<String> items;
    private AbilitySlice slice;
    private final ArrayList<String> statisticNames = new ArrayList<>();
    private long tapStartTime = 0;
    private int lastX;
    private int lastY;
    boolean isFirstMove = false;
    private boolean isDrag;
    public StatisticPanelProvider(ArrayList<String> dataItemList, AbilitySlice slice) {
        this.items = dataItemList;
        this.slice = slice;
    }

    public ArrayList<String> getItems() {
        return items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        Component itemComponent = component;
        TextHolder viewHolder;
        if (itemComponent == null) {
            itemComponent = LayoutScatter.getInstance(slice)
                    .parse(ResourceTable.Layout_item_statistics_web, componentContainer, false);
            viewHolder = new TextHolder(itemComponent);
            itemComponent.setTag(viewHolder);
        } else {
            viewHolder = (TextHolder) itemComponent.getTag();
        }
        Text textView = viewHolder.text;
        WebView webView = viewHolder.webView;
        String item = items.get(position);

        viewHolder.text.setText(item);
        textView.setTextSize(SizeUtils.fp2px(16));
        // if (typeface != null) {
        //     textView.setTypeface(typeface);
        // }
        String name;
        if (position < statisticNames.size()) {
            name = statisticNames.get(position);
        } else {
            name = item;
        }
        textView.setText(name);
        WebConfig settings = webView.getWebConfig();
        settings.setWebStoragePermit(true);
        // settings.setDataAbilityPermit(true);
        // settings.setViewPortFitScreen(true);
        settings.setUserAgent(settings.getUserAgent() + " HarmonyOS");
        // settings.setAutoFitOnLoad(true);
        // settings.setSupportZoom(false);
        // settings.setDataAbilityPermit(true);
        // settings.setLoadsImagesPermit(true);
        settings.setJavaScriptPermit(true);
        webView.setLongClickedListener(component1 -> {
            // webView.setHapticFeedbackEnabled(false); //禁用长按文字操作框
        });
        webView.setOnDragListener((component13, dragEvent) -> true);
        int touchSlop = 24;
        // 模拟点击事件
        webView.setTouchEventListener((component12, touchEvent) -> {
            MmiPoint point = touchEvent.getPointerScreenPosition(0);
            int rawX = (int) point.getX();
            int rawY = (int) point.getY();
            // 处理触摸事件
            switch (touchEvent.getAction()) {
                case TouchEvent.PRIMARY_POINT_DOWN:
                    lastX = rawX;
                    lastY = rawY;
                    tapStartTime = System.currentTimeMillis();
                    isFirstMove = true;
                    isDrag = false;
                    return true;
                case TouchEvent.POINT_MOVE: {
                    int dx = rawX - lastX;
                    int dy = rawY - lastY;
                    //这里修复一些华为手机无法触发点击事件
                    int distance = (int) Math.sqrt(dx * dx + dy * dy);
                    if (!isFirstMove && distance < touchSlop && System.currentTimeMillis() - tapStartTime < 500) {
                        isDrag = false;
                        isFirstMove = false;
                        break;
                    }
                    return false;
                }
                case TouchEvent.PRIMARY_POINT_UP:
                    isFirstMove = false;
                    if(isDrag){
                        // 手指抬起，执行点击逻辑
                        AbilitySlice abilitySlice = new WebViewAbilitySlice();
                        Intent intent = new Intent();
                        intent.setParam(WebViewAbilitySlice.EXTRA_URL, URLConstants.URL_USER_BASE + "/applet");
                        intent.setParam(WebViewAbilitySlice.EXTRA_TITLE, name);
                        slice.present(abilitySlice, intent);
                        return true;
                    }

            }
            return false;
        });
        webView.setBrowserAgent(new BrowserAgent(slice) {
            @Override
            public void onTitleUpdated(WebView webview, String title) {
                HiLog.info(label, "onTitleUpdated title = " + title);
                super.onTitleUpdated(webview, title);
                // 标题变更时自定义处理
                int height = webview.getWebPageHeight();
                HiLog.debug(label, "onTitleUpdated height = " + height + ", title = " + title);
            }

            @Override
            public void onProgressUpdated(WebView webview, int newProgress) {
                HiLog.info(label, "onProgressUpdated newProgress = " + newProgress);
                super.onProgressUpdated(webview, newProgress);
                // 加载进度变更时自定义处理
                int height = webview.getWebPageHeight();
                HiLog.debug(label, "onProgressUpdated height = " + height + ", newProgress = " + newProgress);
            }
        });
        webView.setWebAgent(new WebAgent() {
            @Override
            public void onLoadingPage(WebView webview, String url, PixelMap favicon) {
                HiLog.info(label, "onLoadingPage");
                super.onLoadingPage(webview, url, favicon);
                int height = webview.getWebPageHeight();
                HiLog.debug(label, "onLoadingPage height = " + height);
                // 页面开始加载时自定义处理
            }

            @Override
            public void onPageLoaded(WebView webview, String url) {
                HiLog.info(label, "onPageLoaded");
                super.onPageLoaded(webview, url);
                int height = webview.getWebPageHeight();
                HiLog.debug(label, "onPageLoaded height = " + height);
                // 页面加载结束后自定义处理
            }

            @Override
            public void onLoadingContent(WebView webview, String url) {
                HiLog.info(label, "onLoadingContent");
                super.onLoadingContent(webview, url);
                int height = webview.getWebPageHeight();
                HiLog.debug(label, "onLoadingContent height = " + height);
                // 加载资源时自定义处理
            }

            @Override
            public void onError(WebView webview, ResourceRequest request, ResourceError error) {
                HiLog.info(label, "onError");
                super.onError(webview, request, error);
                // 发生错误时自定义处理
                int height = webview.getWebPageHeight();
                HiLog.debug(label, "onError height = " + height);
            }
        });

        String url = URLConstants.URL_USER_BASE + item;
        HiLog.debug(label, "url = " + url);
        webView.load(url);
        return itemComponent;
    }

    public void setStatisticNames(ArrayList<String> names) {
        statisticNames.clear();
        statisticNames.addAll(names);
    }

    public static class TextHolder {
        Text text;
        WebView webView;

        TextHolder(Component itemComponent) {
            text = itemComponent.findComponentById(ResourceTable.Id_tvTitle);
            webView = itemComponent.findComponentById(ResourceTable.Id_webView);
        }
    }
}